package com.nsqt.biz.controller;

import com.nsqt.biz.domain.AgentDO;
import com.nsqt.biz.domain.ExcelDO;
import com.nsqt.biz.domain.SoftwareDO;
import com.nsqt.biz.service.AgentService;
import com.nsqt.biz.service.SoftwareService;
import com.nsqt.common.utils.*;
import com.nsqt.system.domain.UserDO;
import com.nsqt.system.service.UserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * 软件
 */
@Controller
@RequestMapping("/biz/software")
public class SoftwareController {
    @Autowired
    private SoftwareService softwareService;
    @Autowired
    private AgentService agentService;
    @Autowired
    private UserService userService;

    public static void main(String[] args) {
        //System.out.println(SoftwareController.getIntValue("0.22"));
    }

    @GetMapping()
    @RequiresPermissions("biz:software:software")
    String Software() {
        return "biz/software/software";
    }

    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("biz:software:software")
    public PageUtils list(@RequestParam Map<String, Object> params) {
        Long userId = ShiroUtils.getUserId();
        UserDO user = userService.get(userId);
        List<Long> roles = user.getRoleIds();

        //查询列表数据
        Query query = new Query(params);
        if ((!roles.contains(new Long(1))) && (!roles.contains(new Long(2))) && (!roles.contains(new Long(4)))) {
            query.put("businessMan", userId);
        }
        String agentCompany = (String) query.get("agentCompany");
        if (agentCompany == null || agentCompany.equals("")) {

        } else {

            query.put("agentCompany", agentCompany);
        }
        query.put("sort", "submit_date");
        query.put("order", "desc");
        List<SoftwareDO> softwareList = softwareService.list(query);
	/*	for (SoftwareDO software:softwareList
			 ) {
			if(software.getAgentCompany()==null){

			}else {
				long agentId = software.getAgentCompany();
				AgentDO agent=agentService.get(agentId);
				software.setAgentName(agent.getName());
			}

		}*/
        int total = softwareService.count(query);
        PageUtils pageUtils = new PageUtils(softwareList, total);

        return pageUtils;
    }

    /**
     * 新增软件
     */
    @GetMapping("/add")
    @RequiresPermissions("biz:software:add")
    String add(Model model) {

        Long userId = ShiroUtils.getUserId();
        UserDO user = userService.get(userId);
        List<Long> roles = user.getRoleIds();

        Map map = new HashMap();

        map.put("limit", 200);
        map.put("offset", 0);
        //查询列表数据

        if ((!roles.contains(new Long(1))) && (!roles.contains(new Long(2))) && (!roles.contains(new Long(4)))) {
            map.put("businessMan", userId);
        }
        Query query = new Query(map);
        List<AgentDO> agentList = agentService.list(query);
        model.addAttribute("agentList", agentList);
        List<UserDO> userList = userService.list(new HashMap<>());
        model.addAttribute("userList", userList);

        model.addAttribute("businessMan", user);
        return "biz/software/add";
    }

    /**
     * 发证书
     */
    @GetMapping("/approvals")
    @RequiresPermissions("biz:software:add")
    String approvals(Model model) {

        Long userId = ShiroUtils.getUserId();
        UserDO user = userService.get(userId);
        List<Long> roles = user.getRoleIds();

        Map map = new HashMap();

        map.put("limit", 200);
        map.put("offset", 0);
        //查询列表数据

        if ((!roles.contains(new Long(1))) && (!roles.contains(new Long(2))) && (!roles.contains(new Long(4)))) {
            map.put("businessMan", userId);
        }
        Query query = new Query(map);
        List<AgentDO> agentList = agentService.list(query);
        model.addAttribute("agentList", agentList);
        List<UserDO> userList = userService.list(new HashMap<>());
        SoftwareDO software = softwareService.get(1);


        model.addAttribute("userList", userList);
        model.addAttribute("software", software);
        model.addAttribute("businessMan", user);
        return "biz/software/approvals";
    }

    /**
     * 编辑软件
     */
    @GetMapping("/edit/{id}")
    @RequiresPermissions("biz:software:edit")
    String edit(@PathVariable("id") Integer id, Model model) {

        Long userId = ShiroUtils.getUserId();
        UserDO user = userService.get(userId);
        List<Long> roles = user.getRoleIds();

        Map map = new HashMap();

        map.put("limit", 200);
        map.put("offset", 0);
        //查询列表数据

        if ((!roles.contains(new Long(1))) && (!roles.contains(new Long(2))) && (!roles.contains(new Long(4)))) {
            map.put("businessMan", userId);
        }
        Query query = new Query(map);
        SoftwareDO software = softwareService.get(id);
        if (software.getWorkDays() == null) {
            software.setWorkDays(31);
            software.setPrice("300");
            String approvalDate = DateUtils.date2Str(DateUtils.getDate(new Date(), 30), "YY-MM-dd");

            software.setApprovalDate(approvalDate);
        } else {
            int workDay = software.getWorkDays();
            String approvalDate = DateUtils.date2Str(DateUtils.getDate(new Date(), workDay - 1), "YYYY-MM-dd");
            software.setApprovalDate(approvalDate);

        }
        List<AgentDO> agentList = agentService.list(query);
        model.addAttribute("agentList", agentList);
        List<UserDO> userList = userService.list(new HashMap<>());
        model.addAttribute("userList", userList);
        model.addAttribute("software", software);
        model.addAttribute("businessMan", user);
        return "biz/software/edit";
    }

    /**
     * 编辑软件
     */
    @GetMapping("/presubmit/{id}")
    @RequiresPermissions("biz:software:edit")
    String preSubmit(@PathVariable("id") Integer id, Model model) {

        Long userId = ShiroUtils.getUserId();
        UserDO user = userService.get(userId);
        List<Long> roles = user.getRoleIds();

        Map map = new HashMap();

        map.put("limit", 200);
        map.put("offset", 0);
        //查询列表数据

        if ((!roles.contains(new Long(1))) && (!roles.contains(new Long(2))) && (!roles.contains(new Long(4)))) {
            map.put("businessMan", userId);
        }
        Query query = new Query(map);
        SoftwareDO software = softwareService.get(id);
        if (software.getWorkDays() == null) {
            software.setWorkDays(31);
            software.setPrice("300");
            String approvalDate = DateUtils.date2Str(DateUtils.getDate(new Date(), 30), "YY-MM-dd");

            software.setApprovalDate(approvalDate);
        } else {
            int workDay = software.getWorkDays();
            String approvalDate = DateUtils.date2Str(DateUtils.getDate(new Date(), workDay - 1), "YYYY-MM-dd");
            software.setApprovalDate(approvalDate);

        }
        List<AgentDO> agentList = agentService.list(query);
        model.addAttribute("agentList", agentList);
        List<UserDO> userList = userService.list(new HashMap<>());
        model.addAttribute("userList", userList);
        model.addAttribute("software", software);
        model.addAttribute("businessMan", user);
        return "biz/software/presubmit";
    }

    /**
     * 加载软件
     */
    @GetMapping("/reload/{sn}")
    @RequiresPermissions("biz:software:edit")
    String reload(@PathVariable("sn") String sn, Model model) {

        String params = sn;
        String[] param = sn.split(",");


        SoftwareDO software = softwareService.getBySn(param[0]);
        if (software == null) {
            return "error/notfound";
        }

        String approvalDate = software.getApprovalDate();

        if (approvalDate == null) {

            int workDay = software.getWorkDays();
            Date date = DateUtils.getWorkDay(new Date(), workDay);
            software.setApprovalDate(DateUtils.date2Str(date, "YYYY-MM-dd"));
        }

        software.setNeedSupp(0);
        software.setPrice(String.valueOf(software.getPrice(software.getWorkDays())));
        List<AgentDO> agentList = agentService.list(new HashMap<>());
        model.addAttribute("agentList", agentList);
        List<UserDO> userList = userService.list(new HashMap<>());
        model.addAttribute("userList", userList);
        model.addAttribute("software", software);
        Long userId = ShiroUtils.getUserId();
        UserDO user = userService.get(userId);
        model.addAttribute("businessMan", user);

        return "biz/software/edit";
    }

    /**
     * 更改工作日
     */
    @GetMapping("/changewd/{id}")
    @RequiresPermissions("biz:software:edit")
    String changewd(@PathVariable("id") Integer id, Model model) {
        SoftwareDO software = softwareService.get(id);

        UserDO user = ShiroUtils.getUser();
        String date = DateUtils.date2Str(new Date(), "yyyy-MM-dd");
        software.setComments(software.getComments() + "\n" + user.getName() + "," + date + "操作:" + software.getWorkDays() + "工作日改");
        model.addAttribute("software", software);
        return "biz/software/changewd";
    }

    /**
     * 保存软件
     */
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("biz:software:add")
    public R save(SoftwareDO software) {

        if (softwareService.getBySn(software.getSn()) == null) {
            if (softwareService.save(software) > 0) {
                return R.ok();
            }
        } else {
            return R.error("流水号重复，请查对后再提交。");
        }
        return R.error();
    }

    /**
     * 修改软件
     */
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("biz:software:edit")
    public R update(SoftwareDO software) {
        if (software.getNeedSupp() != null && software.getNeedSupp() == 1) {
            UserDO user = ShiroUtils.getUser();
            String date = DateUtils.date2Str(new Date(), "yyyy-MM-dd");
            software.setSuppReason(user.getName() + "," + date + "操作:" + software.getSuppReason() + "\n");
        }
        softwareService.update(software);
        return R.ok();
    }

    /**
     * 发证
     */
    @PostMapping("/approval")
    @ResponseBody
    @RequiresPermissions("biz:software:edit")
    public R approval(Integer id) {
        if (softwareService.approval(id) > 0) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 发证
     */
    @PostMapping("/bapproval")
    @ResponseBody
    @RequiresPermissions("biz:software:edit")
    public R bapproval(String sn) {
        sn = sn.replaceAll("\r|\n|\t", "");

        if (softwareService.approval(sn) > 0) {
            return R.ok();
        }
        return R.error("未提交证书无法出证");
    }

    /**
     * 发证
     */
    @GetMapping("/approvalsn/{sn}")
    @RequiresPermissions("biz:software:edit")
    public String approvalsn(@PathVariable("sn") String sn, Model model) {
        SoftwareDO software = softwareService.getBySn(sn);
        software.setStatus(3);
        softwareService.update(software);
        List<AgentDO> agentList = agentService.list(new HashMap<>());
        model.addAttribute("agentList", agentList);
        List<UserDO> userList = userService.list(new HashMap<>());
        model.addAttribute("userList", userList);
        model.addAttribute("software", software);
        return "biz/software/approvals";
    }

    /**
     * 取消发证
     */
    @PostMapping("/unApproval")
    @ResponseBody
    @RequiresPermissions("biz:software:edit")
    public R unApproval(Integer id) {
        if (softwareService.unApproval(id) > 0) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 删除软件
     */
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("biz:software:remove")
    public R remove(Integer id) {
        if (softwareService.remove(id) > 0) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 批量删除软件
     */
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("biz:software:batchRemove")
    public R remove(@RequestParam("ids[]") Integer[] ids) {
        softwareService.batchRemove(ids);
        return R.ok();
    }

    /*
     * 导入excel文件
     * @return
     */
    @ResponseBody
    @PostMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        Map resultMap = new HashMap();
        if (file != null) {
            resultMap = saveFile(file);
            if (resultMap.get("code").equals("0")) {
                Map fileMap = new HashMap();
                fileMap.put("src", "");
                resultMap.put("data", fileMap);
                int number = (Integer) resultMap.get("success");
                int repeat = (Integer) resultMap.get("repeat");
                int error = (Integer) resultMap.get("error");
                return R.ok(number + "条记录被成功导入。" + repeat + "条重复记录被忽略。" + error + "条失败。");
            } else {
                return R.error("文件格式不正确。");
            }
        }
        return R.error("您没有上传文件！");
    }

    /**
     * 保存导入的Excel数据到数据库里
     *
     * @param
     * @param file
     */
    public Map saveFile(MultipartFile file) {
        if (file.isEmpty()) {
            return null;
        }
        Map resultMap = new HashMap();
        int number = 0;
        int repeat = 0;
        int error = 0;
        Long userId = ShiroUtils.getUserId();

        List<Object[]> objects = null;
        try {
            objects = ExcelUtils.importExcel(file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
            resultMap.put("code", "2");
            return resultMap;
        }

        for (Object[] os : objects) {
            try {

                SoftwareDO software = new SoftwareDO();
                software.setStatus(0);
                software.setChstatus(0);
                software.setNeedSupp(0);
                software.setBusinessMan(Integer.parseInt(userId.toString()));
                if (os.length > 1) {
                    if (String.valueOf(os[0]) == null) continue;
                    if (String.valueOf(os[0]).trim().equals("")) continue;
                    software.setSn(String.valueOf(os[0]));
                    software.setCopyrightOwner(String.valueOf(os[1]));
                    software.setSoftwareName(String.valueOf(os[2]));

                    software.setAgentCompany(String.valueOf(os[3]).trim());
                    if (software.getAgentCompany() != "" && agentService.getByName(software.getAgentCompany()) == null) {
                        AgentDO agentDO = new AgentDO();
                        agentDO.setName(software.getAgentCompany());
                        agentDO.setBusinessMan(userId.intValue());
                        agentDO.setStatus(0);
                        agentService.save(agentDO);
                    }
                    if (os[4] == null) {
                        software.setWorkDays(31);
                    } else {
                        software.setWorkDays(StringUtils.getIntValue(String.valueOf(os[4])));
                    }
                    if (os[5] == null) {
                        software.setType(0);
                    } else {
                        software.setType(StringUtils.getIntValue(String.valueOf(os[5])));
                    }

                    software.setBusinessMan(userId.intValue());
                    if (softwareService.getBySn(software.getSn()) == null) {
                        softwareService.save(software);
                        number++;
                    } else {
                        //software.setStatus(null);
                        //softwareService.update(software);
                        repeat++;
                    }

                } else {
					/*String whole=(String.valueOf(os[0]));
					String[] strs = whole.split(" ");
					software.setSn(strs[0]);
					software.setCopyrightOwner(strs[1]);
					software.setSoftwareName(strs[2]);*/
                    error++;
                    continue;
                }
            } catch (Exception e) {
                e.printStackTrace();


            }
        }
        resultMap.put("filename", file.getOriginalFilename());
        resultMap.put("saveUrl", "");
        resultMap.put("code", "0");
        System.out.println(number + "条记录导入成功！" + repeat + "条记录重复！");
        //resultMap.put("msg", number+"条记录导入成功！"+repeat+"条记录重复！");
        resultMap.put("success", number);
        resultMap.put("repeat", repeat);
        resultMap.put("error", error);

        return resultMap;


    }

    /**
     * 导出到excel
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/excel")
    @RequiresPermissions("biz:software:software")
    public void exports(HttpServletRequest request, HttpServletResponse response) {
        int rowIndex = 0;

        ExcelDO data = new ExcelDO();
        data.setName("exports");
        List<String> titles = new ArrayList();

        titles.add("交件日期");    //1
        titles.add("流水号");    //2
        titles.add("撤回/转让/改工作日/变更/查询");    //3
        titles.add("撤回流水号");    //4
        titles.add("著作权人");    //5
        titles.add("软著名称");    //6
        titles.add("业务员");    //7
        titles.add("出证日");    //8
        titles.add("实际出证日");    //8
        titles.add("原价（折前价）");    //9
        titles.add("代理公司");    //10
        titles.add("工作日");    //11
        titles.add("是否写材料");    //12
        titles.add("备注");    //13
        titles.add("结算价");//14
        data.setTitles(titles);

        //查询列表数据
        Map map = new HashMap();
        map.put("limit", 10);
        map.put("offset", 20);
        Query query = new Query(map);

        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        String agent = request.getParameter("agentCompany");
        if (startDate == null || startDate.equals("")) {
            startDate = DateUtils.getLastMonthFirstDay();
        }
        if (endDate == null || endDate.equals("")) {
            endDate = DateUtils.getLastMonthLastDay();
        }

        query.put("startDate", startDate);
        query.put("endDate", endDate);
        query.put("agentCompany", agent);

        List<SoftwareDO> softwareList = softwareService.listExcel(query);
        List<List<Object>> rows = new ArrayList();
        for (int i = 0, length = softwareList.size(); i < length; i++) {
            System.out.println("this is the " + i + " software");
            String businessType = "";
            String type = "";
            String businessMan = "";
            String agentCompany = "";
            SoftwareDO software = softwareList.get(i);
            List<Object> row = new ArrayList();
            row.add(software.getSubmitDate());
            row.add(software.getSn());
            if (software.getBusinessType() != null) {
                switch (software.getBusinessType()) {
                    case 0:
                        businessType = "新登记";
                        break;
                    case 1:
                        businessType = "转让";
                        break;
                    case 2:
                        businessType = "变更";
                        break;
                    case 3:
                        businessType = "查询";
                        break;
                    case 4:
                        businessType = "撤回";
                        break;
                    default:
                        businessType = "新登记";
                }
            } else {
                businessType = "新登记";
            }
            row.add(businessType);
            row.add(software.getBacksn());
            row.add(software.getCopyrightOwner());
            row.add(software.getSoftwareName());

		/*	if(software.getBusinessMan()!=null){
				long userId = software.getBusinessMan();
				UserDO user=userService.get(userId);
				businessMan=user.getName();
			}*/
            row.add(software.getBusinessManName());
            row.add(software.getApprovalDate());
            row.add(software.getApprovalTime());
            row.add(software.getPrice());

            row.add(software.getAgentCompany());
            row.add(software.getWorkDays());
            if (software.getType() == null) {
                type = "否";

            } else if (software.getType() == 0) {
                type = "否";
            } else {
                type = "是";
            }
            row.add(type);
            row.add(software.getComments());
/*			AgentDO agentDO=agentService.getByName(software.getAgentCompany());
			if(agentDO==null){
				row.add("");
			}else {
				row.add(getRealPrice(agentDO, software.getWorkDays()));
			}*/
            switch (software.getWorkDays()) {
                case 31:
                    row.add(software.getPrice31());
                    break;
                case 26:
                    row.add(software.getPrice26());
                    break;
                case 21:
                    row.add(software.getPrice21());
                    break;
                case 16:
                    row.add(software.getPrice16());
                    break;
                case 11:
                    row.add(software.getPrice11());
                    break;
                case 6:
                    row.add(software.getPrice6());
                    break;
                case 5:
                    row.add(software.getPrice5());
                    break;
                case 4:
                    row.add(software.getPrice4());
                    break;
                case 3:
                    row.add(software.getPrice3());
                    break;
                case 2:
                    row.add(software.getPrice2());
                    break;
                case 1:
                    row.add(software.getPrice1());
                    break;
                default:
                    row.add(0);
                    break;
            }
            rows.add(row);
        }
        data.setRows(rows);
        try {
            String fileName = startDate + "to" + endDate;
            ExcelUtils.exportExcel(response, fileName, data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public int getRealPrice(AgentDO agent, int workDays) {

        int realPrice = 0;

        switch (workDays) {
            case 31:
                realPrice = (agent.getPrice31() == null ? 0 : agent.getPrice31());
                break;
            case 26:
                realPrice = (agent.getPrice26() == null ? 0 : agent.getPrice26());
                break;
            case 21:
                realPrice = (agent.getPrice21() == null ? 0 : agent.getPrice21());
                break;
            case 16:
                realPrice = (agent.getPrice16() == null ? 0 : agent.getPrice16());
                break;
            case 11:
                realPrice = (agent.getPrice11() == null ? 0 : agent.getPrice11());
                break;
            case 6:
                realPrice = (agent.getPrice6() == null ? 0 : agent.getPrice6());
                break;
            case 5:
                realPrice = (agent.getPrice5() == null ? 0 : agent.getPrice5());
                break;
            case 4:
                realPrice = (agent.getPrice4() == null ? 0 : agent.getPrice4());
                break;
            case 3:
                realPrice = (agent.getPrice3() == null ? 0 : agent.getPrice3());
                break;
            case 2:
                realPrice = (agent.getPrice2() == null ? 0 : agent.getPrice2());
                break;
            case 1:
                realPrice = (agent.getPrice1() == null ? 0 : agent.getPrice1());
                break;
            default:
                realPrice = 0;
                break;
        }
        return realPrice;

    }

}
